﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Inovout.Web.Mvc
{
    public class WidgetModelMetadataProvider : CachedDataAnnotationsModelMetadataProvider
    {
        private bool CanCreateWidgetCollectionModelMetadata(Type modelType)
        {
            //string也是继续IEnumerable
            return typeof(IEnumerable).IsAssignableFrom(modelType) && !typeof(string).Equals(modelType);
        }
        protected override CachedDataAnnotationsModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)
        {
            //根据Model原始特性缓存，只有第一次会执行，之后每次请求都不会再创建。
            if (CanCreateWidgetCollectionModelMetadata(modelType))
            {
                return new WidgetCollectionModelMetadata(this, containerType, modelType, propertyName, attributes);
            }
            else
            {
                return new WidgetModelMetadata(this, containerType, modelType, propertyName, attributes);
            }
        }

        protected override CachedDataAnnotationsModelMetadata CreateMetadataFromPrototype(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor)
        {
            //根据ModelType   
            if (CanCreateWidgetCollectionModelMetadata(prototype.ModelType))
            {
                return new WidgetCollectionModelMetadata(prototype, modelAccessor);
            }
            else
            {
                return new WidgetModelMetadata(prototype, modelAccessor);
            }
        }
    }
}
